/*
 * @lc app=leetcode.cn id=1779 lang=typescript
 *
 * [1779] 找到最近的有相同 X 或 Y 坐标的点
 */

// @lc code=start
function nearestValidPoint(x: number, y: number, points: number[][]): number {
  const n = points.length;
  let minDist = Number.POSITIVE_INFINITY;
  let ans = -1;

  for (let i = 0; i < n; i++) {
    const [px, py] = points[i];
    if (px === x || py === y) {
      const manhattanDist = Math.abs(x - px) + Math.abs(y - py);
      if (minDist > manhattanDist) {
        minDist = manhattanDist;
        ans = i;
      }
    }
  }

  return ans;
}
// @lc code=end
